<template>
  <div class="course-detail-container">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-mask">
      <el-icon class="loading-spinner" :size="30"><Loading /></el-icon>
      <p>加载课程详情中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-message">
      <el-icon><WarningFilled /></el-icon>
      <p>{{ error.message }}</p>
      <el-button type="primary" @click="fetchCourseDetail">重试</el-button>
    </div>

    <!-- 课程详情内容 -->
    <div v-else class="course-content">
      <!-- 返回按钮 -->
      <el-button type="text" @click="goBack" class="back-button">
        <el-icon><ArrowLeft /></el-icon> 返回课程列表
      </el-button>

      <!-- 课程信息卡片 -->
      <el-card class="course-info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h2 class="course-title">{{ courseData.couName }}</h2>
            <el-tag :type="courseData.couPrice === 0 ? 'success' : 'warning'">
              {{ courseData.couPrice === 0 ? '免费课程' : `¥${courseData.couPrice}` }}
            </el-tag>
          </div>
        </template>
        
        <div class="course-meta">
          <div class="meta-item">
            <el-icon><User /></el-icon>
            <span>教师ID：{{ courseData.teaId }}</span>
          </div>
        </div>
        
        <div class="course-intro">
          <h3>课程简介</h3>
          <p>{{ courseData.couIntroduction || '暂无课程简介' }}</p>
        </div>
        
        <div class="course-stats">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <el-icon><Collection /></el-icon>
                <div>
                  <div class="stat-value">{{ courseData.chapters?.length || 0 }}</div>
                  <div class="stat-label">章节数</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <el-icon><View /></el-icon>
                <div>
                  <div class="stat-value">{{ courseData.clicks || 0 }}</div>
                  <div class="stat-label">浏览量</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <el-icon><ShoppingCart /></el-icon>
                <div>
                  <div class="stat-value">{{ courseData.purchase || 0 }}</div>
                  <div class="stat-label">购买量</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <div>
                  <div class="stat-value">{{ courseData.couLikeNum || 0 }}</div>
                  <div class="stat-label">点赞数</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 章节列表 -->
      <el-card class="section-card" shadow="hover">
        <template #header>
          <div class="section-header">
            <h3>课程章节（{{ courseData.chapters?.length || 0 }}节）</h3>
            <el-button type="primary" size="small" @click="goToChapterManagement(courseId)">
              管理章节
            </el-button>
          </div>
        </template>
        
        <div v-if="courseData.chapters && courseData.chapters.length > 0">
          <el-table 
            :data="sortedChapters" 
            stripe 
            v-loading="chapterLoading"
            element-loading-text="加载章节中..."
            style="width: 100%"
          >
            <el-table-column type="index" width="120" label="序号"></el-table-column>
            <el-table-column prop="title" label="章节标题">
              <template #default="scope">
                {{ scope.row.title || '未命名章节' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-empty v-else description="暂无课程章节" />
      </el-card>
      
      <!-- 学生列表 -->
      <el-card class="section-card" shadow="hover">
        <template #header>
          <div class="section-header">
            <h3>选课学生（{{ courseData.students?.length || 0 }}人）</h3>
            <div>
              <el-button type="primary" size="small" @click="showAddStudentDialog">
                添加学生
              </el-button>
              <el-button type="danger" size="small" @click="showBatchRemoveDialog" 
                        :disabled="selectedStudentIds.length === 0">
                批量移除
              </el-button>
            </div>
          </div>
        </template>
        
        <div v-if="courseData.students && courseData.students.length > 0">
          <el-table 
            :data="courseData.students" 
            v-loading="studentLoading"
            element-loading-text="加载学生中..."
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="stuName" label="学生姓名" width="180"></el-table-column>
            <el-table-column prop="stuId" label="学生ID" width="180"></el-table-column>
            <el-table-column label="加入时间">
              <template #default="scope">
                {{ scope.row.joinTime ? formatDateTime(scope.row.joinTime) : '未记录' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeStudent(scope.row.stuId)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-empty v-else description="暂无选课学生" />
      </el-card>

      <!-- 班级列表 -->
      <el-card class="section-card" shadow="hover">
        <template #header>
          <h3>关联班级（{{ uniqueClasses.length }}个）</h3>
        </template>
        
        <div v-if="uniqueClasses.length > 0" class="class-tags">
          <el-tag
            v-for="cls in uniqueClasses"
            :key="cls.id"
            type="success"
            class="class-tag"
          >
            {{ cls.className || '未命名班级' }}
          </el-tag>
        </div>
        
        <el-empty v-else description="暂无关联班级" />
      </el-card>

      <!-- 课程评论 -->
      <el-card class="section-card" shadow="hover">
        <template #header>
          <h3>课程评论（{{ courseData.comments?.length || 0 }}条）</h3>
        </template>
        
        <div v-if="courseData.comments && courseData.comments.length > 0">
          <div 
            v-for="comment in courseData.comments"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-header">
              <el-avatar 
                :src="comment.studentId ? require('@/assets/fault.png') : ''"
                size="small"
              ></el-avatar>
              <div class="comment-author">
                {{ comment.studentName || '匿名用户' }}
                <div class="comment-time">
                  {{ comment.createTime ? formatDateTime(comment.createTime) : '未记录' }}
                </div>
              </div>
            </div>
            
            <div class="comment-content">
              <p>{{ comment.content || '无内容' }}</p>
              <div class="comment-score">
                <el-rate
                  :disabled="true"
                  :model-value="comment.score ? parseInt(comment.score) : 0"
                  text-color="#ffd700"
                ></el-rate>
              </div>
            </div>
          </div>
        </div>
        
        <el-empty v-else description="暂无课程评论" />
      </el-card>
    </div>

    <!-- 添加学生对话框 -->
    <el-dialog
      v-model="addStudentDialogVisible"
      title="添加学生到课程"
      width="50%"
    >
      <div class="dialog-content">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="输入学生姓名或ID搜索"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        
        <el-table
          :data="filteredStudents"
          height="400"
          style="width: 100%"
          @selection-change="handleStudentSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="stuId" label="学生ID" width="120"></el-table-column>
          <el-table-column prop="stuName" label="学生姓名"></el-table-column>
        </el-table>
        
        <div class="dialog-footer">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="totalStudents"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addStudentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddStudents">确认添加</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 批量移除确认对话框 -->
    <el-dialog
      v-model="batchRemoveDialogVisible"
      title="确认移除学生"
      width="30%"
    >
      <p>确定要从课程中移除选中的 {{ selectedStudentIds.length }} 名学生吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchRemoveDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmBatchRemove">确认移除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  ElMessage, 
  ElCard, 
  ElTable, 
  ElTableColumn,
  ElTag,
  ElButton,
  ElIcon,
  ElEmpty,
  ElRate,
  ElAvatar,
  ElRow,
  ElCol,
  ElDialog,
  ElInput,
  ElPagination,
  ElInputNumber
} from 'element-plus';
import {
  ArrowLeft,
  User,
  View,
  Star,
  ShoppingCart,
  Collection,
  WarningFilled,
  Loading,
  Search
} from '@element-plus/icons-vue';
import axios from 'axios';
import { studentApi } from '@/api/students';

// 状态管理
const isLoading = ref(true);
const error = ref(null);
const courseData = ref({});
const chapterLoading = ref(false);
const studentLoading = ref(false);
const addStudentDialogVisible = ref(false);
const batchRemoveDialogVisible = ref(false);
const selectedStudentIds = ref([]);
const selectedStudents = ref([]);
const allStudents = ref([]);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);

// 路由
const route = useRoute();
const router = useRouter();
const courseId = route.params.id;

// 计算属性：按sortOrder排序的章节
const sortedChapters = computed(() => {
  if (!courseData.value.chapters) return [];
  
  // 深拷贝避免直接修改原数据
  const chapters = JSON.parse(JSON.stringify(courseData.value.chapters));
  
  // 确保所有章节都有sortOrder属性
  chapters.forEach(chapter => {
    if (typeof chapter.sortOrder === 'undefined') {
      chapter.sortOrder = chapter.index || 0;
    }
  });
  
  // 按sortOrder升序排序
  return chapters.sort((a, b) => a.sortOrder - b.sortOrder);
});

// 计算属性：班级去重
const uniqueClasses = computed(() => {
  if (!courseData.value?.classes) return [];
  const seen = new Set();
  return courseData.value.classes.filter(cls => {
    if (seen.has(cls.id)) return false;
    seen.add(cls.id);
    return true;
  });
});

// 计算属性：过滤学生列表
const filteredStudents = computed(() => {
  if (!searchKeyword.value) {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = currentPage.value * pageSize.value;
    return allStudents.value.slice(start, end);
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  return allStudents.value.filter(student => {
    return (student.stuName?.toLowerCase().includes(keyword) || 
           student.stuId?.toString().includes(keyword));
  });
});

// 计算属性：学生总数
const totalStudents = computed(() => {
  return searchKeyword.value 
    ? filteredStudents.value.length 
    : allStudents.value.length;
});

// 日期格式化函数
const formatDateTime = (dateString) => {
  if (!dateString) return '未记录';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 更新章节排序序号
const updateChapterSortOrder = async (chapter) => {
  try {
    await axios.put(`/spoc/vod/teacher/chapter/${chapter.id}`, {
      sortOrder: chapter.sortOrder
    });
    ElMessage.success('排序序号更新成功');
    await fetchCourseDetail(); // 重新加载数据保持一致性
  } catch (err) {
    console.error('更新排序序号失败:', err);
    ElMessage.error('更新排序序号失败');
  }
};

// API调用函数
const fetchCourseDetail = async () => {
  try {
    isLoading.value = true;
    error.value = null;
    chapterLoading.value = true;
    studentLoading.value = true;

    const { data } = await axios.get(`/spoc/vod/teacher/course/${courseId}/detail`);
    console.log('API响应数据:', data);
    
    if (!data) throw new Error('课程详情数据为空');

    // 处理章节数据，确保字段名一致
    const processedChapters = (data.chapters || []).map(chapter => ({
      id: chapter.id,
      courseId: chapter.courseId,
      index: chapter.index,
      title: chapter.title || '未命名章节',
      url: chapter.url || null,
      sortOrder: chapter.sortOrder ?? chapter.index ?? 0, // 优先使用sortOrder，其次使用index
      createTime: chapter.createTime,
      updateTime: chapter.updateTime
    }));

    courseData.value = {
      ...data,
      chapters: processedChapters
    };

  } catch (err) {
    console.error('课程详情加载失败:', err);
    error.value = { 
      message: '加载课程详情失败，请重试', 
      details: err.message || '网络请求失败' 
    };
    ElMessage.error(error.value.message);
  } finally {
    isLoading.value = false;
    chapterLoading.value = false;
    studentLoading.value = false;
  }
};

// 显示添加学生对话框
const showAddStudentDialog = async () => {
  try {
    const response = await studentApi.getAllStudents();
    
    // 处理不同响应结构
    let students = [];
    if (Array.isArray(response)) {
      students = response;
    } else if (response?.data) {
      students = Array.isArray(response.data.list) ? response.data.list : response.data;
    }
    
    // 确保学生数据有正确的字段名
    allStudents.value = students.map(student => ({
      stuId: student.stuId || student.id,
      stuName: student.stuName || student.name
    }));
    
    addStudentDialogVisible.value = true;
  } catch (err) {
    ElMessage.error(`获取学生列表失败: ${err.message}`);
  }
};

// 处理学生选择
const handleStudentSelectionChange = (selection) => {
  selectedStudents.value = selection.map(s => s.stuId);
};

// 确认添加学生
const confirmAddStudents = async () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请至少选择一名学生');
    return;
  }

  try {
    const successStudents = [];
    const alreadyInCourseStudents = [];
    
    for (const studentId of selectedStudents.value) {
      try {
        const params = new URLSearchParams();
        params.append('studentId', studentId);
        
        await axios.post(
          `/spoc/vod/teacher/course/${courseId}/students`,
          params,
          { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
        );
        successStudents.push(studentId);
      } catch (err) {
        if (err.response?.status === 400 && 
            err.response?.data === '该学生已经加入本课程') {
          const student = allStudents.value.find(s => s.stuId === studentId);
          alreadyInCourseStudents.push(student?.stuName || studentId);
        } else {
          throw err;
        }
      }
    }
    
    let message = '';
    if (successStudents.length > 0) {
      message += `成功添加 ${successStudents.length} 名学生\n`;
    }
    if (alreadyInCourseStudents.length > 0) {
      message += `以下学生已在本课程中:\n${alreadyInCourseStudents.join('\n')}`;
    }
    
    ElMessage({
      message: message,
      type: 'success',
      duration: 5000,
      showClose: true
    });
    
    addStudentDialogVisible.value = false;
    await fetchCourseDetail();
    
  } catch (err) {
    console.error('添加学生失败:', err);
    const errorMsg = err.response?.data?.message || err.message || '添加学生失败';
    ElMessage.error(errorMsg);
  }
};

// 显示批量移除对话框
const showBatchRemoveDialog = () => {
  if (selectedStudentIds.value.length === 0) {
    ElMessage.warning('请至少选择一名学生');
    return;
  }
  batchRemoveDialogVisible.value = true;
};

// 确认批量移除
const confirmBatchRemove = async () => {
  try {
    if (selectedStudentIds.value.length === 1) {
      await axios.delete(
        `/spoc/vod/teacher/course/${courseId}/students/${selectedStudentIds.value[0]}`
      );
    } else {
      await axios.delete(
        `/spoc/vod/teacher/course/${courseId}/students/batch`,
        { data: selectedStudentIds.value }
      );
    }
    
    ElMessage.success('移除学生成功');
    batchRemoveDialogVisible.value = false;
    selectedStudentIds.value = [];
    await fetchCourseDetail();
  } catch (err) {
    ElMessage.error('移除学生失败');
  }
};

// 移除单个学生
const removeStudent = async (studentId) => {
  try {
    await axios.delete(`/spoc/vod/teacher/course/${courseId}/students/${studentId}`);
    ElMessage.success('移除学生成功');
    await fetchCourseDetail();
  } catch (err) {
    ElMessage.error('移除学生失败');
  }
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedStudentIds.value = selection.map(item => item.stuId);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 处理搜索清除
const handleSearchClear = () => {
  searchKeyword.value = '';
  currentPage.value = 1;
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 播放视频方法
const playVideo = (chapter) => {
  if (!chapter.url) {
    ElMessage.warning('该章节没有视频内容');
    return;
  }
  
  router.push({
    path: '/video-player',
    query: {
      courseId: courseId,
      chapterId: chapter.id
    }
  });
};

// 导航方法
const goBack = () => {
  router.push('/teacher/courses');
};

// 跳转到章节管理页面
const goToChapterManagement = (courseId) => {
  router.push(`/course/chapter/${courseId}`);
};

// 初始化加载数据
onMounted(() => {
  fetchCourseDetail();
});
</script>

<style scoped>
.course-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading-mask {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.loading-spinner {
  margin-bottom: 20px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #f56c6c;
}

.error-message .el-icon {
  font-size: 50px;
  margin-bottom: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.course-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-title {
  margin: 0;
  font-size: 24px;
}

.course-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.course-intro {
  margin-bottom: 20px;
}

.course-intro h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
}

.course-stats {
  margin-top: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.stat-item .el-icon {
  font-size: 24px;
  color: #409eff;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.section-card {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.class-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.class-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.comment-author {
  margin-left: 10px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  margin-left: 42px;
}

.comment-content p {
  margin: 5px 0;
}

.comment-score {
  margin-top: 5px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .course-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .stat-item {
    justify-content: center;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>